package com.twotiger.and.activity.others;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import app.twotiger.p2p.R;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.BitmapUtils;
import com.twotiger.and.Constants;
import com.twotiger.and.activity.WebViewPage;
import com.twotiger.and.activity.base.AbastractListItem;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.activity.base.BaseListItem;
import com.twotiger.and.activity.base.SubTitle;
import com.twotiger.and.activity.user.LoginPage;
import com.twotiger.and.adapter.BaseListAdapter;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.BroswerUrl;
import com.twotiger.and.bean.ConstantDataUnit;
import com.twotiger.and.bean.Contact;
import com.twotiger.and.bean.Share;
import com.twotiger.and.bean.User;
import com.twotiger.and.util.EaseHXUtils;
import com.twotiger.and.util.IntentUtil;
import com.twotiger.and.util.PackageUtils;
import com.twotiger.and.util.PromptManager;
import com.twotiger.and.util.PromptManager.ClickListener;
import com.twotiger.and.util.PromptManager.ReChargeClickListener;
import com.twotiger.and.util.StringUtils;
import com.twotiger.and.util.TimeUtils;
import com.twotiger.and.util.UmShearUtils;
import com.twotiger.and.util.ViewUtils;
import com.twotiger.and.view.UnConflictListView;

public class MorePage extends BaseActivity {

    private static final int GETUSERINFOSSUCESS = 0;
    private static final int GETUSERINFOFAIL = 1;
    private static final int OPENPAYMENTSUCCES = 2;
    private static final int OPENPAYMENTFAIL = 4;
    private static final int GETSHARESUCCESS = 5;
    private static final int GETSHAREFAILURE = 6;
    private static final int GETCONTACTSUCCESS = 7;
    private static final int GETCONTACTFAILURE = 8;

    private UnConflictListView baseList;
    private BaseListAdapter baseListaAdapter;
    private SubTitle subTitle;

    private View view;
    private ImageView user_big_icon;
    private TextView phone_number;
    private TextView name;
    private HashMap<String, String> parms;
    private BaseHandler handler;
    private RelativeLayout acount_layout;
    private TextView exit_acount;
    private TextView tv_version;

    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        view = inflater.inflate(R.layout.more_page_layout, null);
        return view;
    }

    @Override
    protected void findViewById(View view) {

        subTitle = new SubTitle(view) {
            @Override
            protected void clickTitle(View v) {
            }

            @Override
            protected void clickRightBtn(View v) {
            }

            @Override
            protected void cickLeftBtn(View v) {
                onBackPress();
            }
        };
        subTitle.setTitle("更多设置");
        subTitle.hideBtns();
        subTitle.title_left_bt.setVisibility(View.VISIBLE);

        exit_acount = (TextView) view.findViewById(R.id.exit_acount);
        baseList = (UnConflictListView) view.findViewById(R.id.base_list);
        phone_number = (TextView) view.findViewById(R.id.phone_number);
        name = (TextView) view.findViewById(R.id.name);
        user_big_icon = (ImageView) view.findViewById(R.id.user_big_icon);
        acount_layout = (RelativeLayout) view.findViewById(R.id.acount_layout);
        tv_version = (TextView) view.findViewById(R.id.tv_version);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.exit_acount:
            PromptManager.showMyAlert(mContext, "确认退出当前账号？", "确定", "取消",
                new ReChargeClickListener() {

                    @Override
                    public void onClickConfirm() {
                        application.logout();
                        Intent intent = new Intent(getContext(), LoginPage.class).putExtra("FROM",
                            R.id.exit_acount);
                        startNewActivity(intent, R.anim.slide_in_from_bottom, R.anim.silent_anim,
                            true);
                    }

                    @Override
                    public void onClickCancel() {

                    }
                }, true);
            break;
        case R.id.acount_layout:
            if (!isLogin()) {
                Intent intent = new Intent(MorePage.this, LoginPage.class);
                intent.putExtra("FROM", R.id.acount_layout);
                startNewActivity(intent, R.anim.slide_in_from_bottom, R.anim.silent_anim, false);
                return;
            }
            if (!hasOpenThirdAct()) {
                getOpenpayament();
                return;
            }
            startNewActivity(new Intent(MorePage.this, AccountSetting.class), R.anim.push_left_in,
                R.anim.push_left_out, false);
            break;
        case R.id.call_phone:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            IntentUtil.CallPhone(MorePage.this, Constants.PHONE_NUM);
            break;
        default:
            break;
        }
    }

    @Override
    protected void setListener() {
        handler = new BaseHandler(MorePage.this) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case GETUSERINFOSSUCESS:
                    Basebean result = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result.isOk()) {
                        User user = JSON.parseObject(result.data, User.class);
                        MorePage.this.application.setUser(user);
                        if (!StringUtils.isEmpty(user.avatar)) {
                            BitmapUtils utils = new BitmapUtils(MorePage.this);
                            utils.display(user_big_icon, user.avatar);
                        }
                        phone_number.setVisibility(View.VISIBLE);
                        phone_number.setText(user.phone);
                        if (user.hasOpenThirdAct) {
                            name.setText(user.name);
                        } else {
                            name.setText("HI,匿名君,实名认证一下吧~");
                        }
                    } else {
                        showToast(result.codeDesc);
                    }
                    break;
                case GETUSERINFOFAIL:

                    break;
                case OPENPAYMENTSUCCES:
                    Basebean result_open = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_open.isOk()) {
                        BroswerUrl responseinfo = JSON.parseObject(result_open.data,
                            BroswerUrl.class);
                        Intent intent = new Intent(MorePage.this, WebViewPage.class);
                        intent.putExtra("title", "汇付天下托管账号");
                        intent.putExtra("url", responseinfo.getUrl());
                        intent.putExtra("BUSINESS_TYPE", WebViewPage.TYPE_PAYMENT_REGIST);
                        startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
                    } else {
                        showToast(result_open.codeDesc);
                    }
                    break;
                case OPENPAYMENTFAIL:

                    break;
                case GETSHARESUCCESS:
                    Basebean result_s = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_s.isOk()) {
                        Share shareInfo = JSONObject.parseObject(result_s.data, Share.class);
                        String title = shareInfo.getTitle();
                        String content = shareInfo.getContent();
                        String url = shareInfo.getUrl();
                        String pic = shareInfo.getPic();
                        UmShearUtils.shear(MorePage.this, url, true, title, content, pic);
                    } else {
                        showToast(result_s.codeDesc);
                    }
                    break;
                case GETSHAREFAILURE:
                    showToast("网络异常");
                    break;
                case GETCONTACTSUCCESS:
                    Contact mContact = JSONObject.parseObject((String) msg.obj, Contact.class);
                    if (mContact.isOk()) {
                        //                        String url11 = "mqqwpa://im/chat?chat_type=wpa&uin="+"938026468"+"&version=1";
                        //                        String url11 = "mqqapi://card/show_pslcard?uin=938026468&account_flag=0&card_type=crm&jumptype=1";

                        String qqServUrl = mContact.getQqServUrl();
                        String qqType = mContact.getQqType();
                        if ("personal".equals(qqType)) { //需根据时间弹窗
                            String timeNow = TimeUtils.getFormatTime1();
                            String qqServTime = mContact.getQqServTime();
                            String[] timeArray = qqServTime.split("-");
                            int nowTimeToMinute = TimeUtils.timeToMinute(timeNow);
                            int qqServTimePreToMinute = TimeUtils.timeToMinute(timeArray[0]);
                            int qqServTimeEndToMinute = TimeUtils.timeToMinute(timeArray[1]);
                            if (nowTimeToMinute < qqServTimePreToMinute
                                || nowTimeToMinute > qqServTimeEndToMinute) {
                                PromptManager.showContactAlert(MorePage.this, "工作时间：" + qqServTime
                                                                              + "\n请在工作时间联系哦",
                                    "我知道了", "", new ClickListener() {

                                        @Override
                                        public void onClickRight() {
                                        }

                                        @Override
                                        public void onClickLeft() {
                                        }
                                    }, false);
                            } else {
                                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(qqServUrl));
                                if (IntentUtil.queryIntentActivities(MorePage.this, intent)) {
                                    startNewActivity(intent, R.anim.push_left_in,
                                        R.anim.push_left_out, false);
                                } else {
                                    showToast("您的手机还未安装QQ,请先下载QQ");
                                }
                            }
                        } else { //直接进入聊天，无需再根据时间判断是否弹窗
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(qqServUrl));
                            if (IntentUtil.queryIntentActivities(MorePage.this, intent)) {
                                startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out,
                                    false);
                            } else {
                                showToast("您的手机还未安装QQ,请先下载QQ");
                            }
                        }

                    } else {
                        showToast(mContact.codeDesc);
                    }
                    break;
                case GETCONTACTFAILURE:
                    showToast("网络异常");
                    break;
                default:
                    break;
                }
                super.handleMessage(msg);
            }
        };
        acount_layout.setOnClickListener(this);
        exit_acount.setOnClickListener(this);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (!isLogin()) {
            phone_number.setVisibility(View.GONE);
            name.setText("登录/注册");
            exit_acount.setVisibility(View.GONE);
        }
        if (isLogin()) {
            exit_acount.setVisibility(View.VISIBLE);
            getuserinfo();
        }
    }

    @Override
    protected void processLogic() {
        parms = getParm();
        if (!isLogin()) {
            phone_number.setVisibility(View.GONE);
            name.setText("登录/注册");
            exit_acount.setVisibility(View.GONE);
        }
        if (isLogin()) {
            getuserinfo();
        }
        tv_version.setText("版本号：" + PackageUtils.getAppVersionName(this));

        ArrayList<AbastractListItem> datas = new ArrayList<AbastractListItem>();
        datas.add(new BaseListItem("安全保障", R.drawable.safeprotect, true,
            new BaseListItem.OnClick() {
                @Override
                public void onClick() {
                    ConstantDataUnit dz_aqbz = MorePage.this.getConstantDataByKey(Constants.dz_aqbz);
                    if(dz_aqbz != null){
                        Intent intent = new Intent(MorePage.this, WebViewPage.class);
                        intent.putExtra("title", dz_aqbz.getName());
                        intent.putExtra("url", dz_aqbz.getVal());
                        startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
                    }
                }
            }));
        datas.add(new BaseListItem("平台介绍", R.drawable.platform_introduce, false,
            new BaseListItem.OnClick() {
                @Override
                public void onClick() {
                    ConstantDataUnit dz_gywm = MorePage.this.getConstantDataByKey(Constants.dz_gywm);
                    if(dz_gywm != null){
                        Intent intent = new Intent(MorePage.this, WebViewPage.class);
                        intent.putExtra("title", dz_gywm.getName());
                        intent.putExtra("url", dz_gywm.getVal());
                        startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
                    }
                }
            }));

        datas.add(new BaseListItem("常见问题", R.drawable.normal_questtion, true, new ItemClick(
            ConmonQuestionPage.class)));
        datas.add(new BaseListItem("在线客服", R.drawable.online_service, false,
            new BaseListItem.OnClick() {
                @Override
                public void onClick() {

                    // getContact();
                    new EaseHXUtils().startEaseChat(mContext);

                }
            }));
        datas.add(new BaseListItem("意见反馈", R.drawable.feed_back, false, new ItemClick(
            FeedBackPage.class)));

        datas.add(new BaseListItem("分享app", R.drawable.share, true, new BaseListItem.OnClick() {
            @Override
            public void onClick() {

                gotoShare();
            }
        }));

        baseListaAdapter = new BaseListAdapter(MorePage.this, datas);
        baseList.setAdapter(baseListaAdapter);
    }

    protected void getContact() {
//        parms.clear();
//        getDate(parms, Constants.constant_query, handler, GETCONTACTSUCCESS, GETCONTACTFAILURE,
//            true, false, false);
    }

    protected void gotoShare() {
        parms.clear();
        getDate(parms, Constants.SHARE, handler, GETSHARESUCCESS, GETSHAREFAILURE, true, false,
            false);
    }

    /**
     * 获取用户信息
     */
    private void getuserinfo() {
        parms.clear();
        parms.put("token", getToken());
        getDate(parms, Constants.USERINFOQUERY, handler, GETUSERINFOSSUCESS, GETUSERINFOFAIL,
            false, false, false);
    }

    private void getOpenpayament() {
        parms.clear();
        parms.put("token", getToken());
        getDate(parms, Constants.REGISTHF, handler, OPENPAYMENTSUCCES, OPENPAYMENTFAIL, true,
            false, false);
    }

    class ItemClick implements BaseListItem.OnClick {
        private Class<? extends Activity> clazz;

        public ItemClick(Class<? extends Activity> clazz) {
            this.clazz = clazz;
        }

        @Override
        public void onClick() {
            Intent intent = new Intent(MorePage.this, clazz);
            startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
        }

    }

    @Override
    protected void onBackPress() {
        finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

}
